<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="primary" @click="handleSearch()" >
          查询
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" >
          重置
        </el-button>
      </div>

      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <!-- <el-form :inline="true" :model="listQuery" size="small" label-width="140px"> -->
          <div style="display: inline-block;margin-left:20px;margin-right: 30px;">
            <el-form-item label="货品名:">
              <el-input v-model="searchForm.name" class="input-width" placeholder="商品名" clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px;margin-right: 30px;">
            <el-form-item label="关键字:">
              <el-input v-model="searchForm.keywords" class="input-width" placeholder="关键字" clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px;margin-right: 30px;">
            <el-form-item label="货品类目:">
              <el-tree-select v-model="searchForm.productCategoryId" :data="productCategoryOptions"
                :render-after-expand="false" style="width: 120px" clearable />
              <!-- <el-input v-model="searchForm.keywords" class="input-width" placeholder="商品类目"></el-input> -->
            </el-form-item>
          </div>

        </el-form>
      </div>
    </el-card>
  </div>
<div>
  <el-table :data="tableData.list" style="margin-top: 10px;" border stripe>
    <el-table-column prop="productCategoryName" label="货品类目"></el-table-column>
    <el-table-column prop="name" label="货品名称"></el-table-column>
    <el-table-column prop="price" label="价格" >
  </el-table-column>
    <el-table-column prop="unit" label="单位"></el-table-column>
    <!-- <el-table-column prop="priceRules" label="货品价格规则"> 
      <template #default="{ row }">
    <div v-for="(rule, index) of parsePriceRules(row.priceRules)" :key="index">
          {{ rule.key }}: {{ rule.value }}
        </div>
    </template>
    </el-table-column> -->
    <!-- <el-table-column prop="priceRules" label="货品价格规则列表"></el-table-column> -->
    <el-table-column prop="note" label="备注信息"></el-table-column>

    <el-table-column label="操作" >
      <template #default="scope">
        <el-button link type="primary" size="small" @click="open(scope.row)">
          编辑商品
        </el-button>
        <el-button
          size="small"
          type="text"
          @click="() => handleDelete(scope.row)">删除商品
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="编辑商品信息">
    <el-form ref="formRef" :model="updateForm" :rules="rules">
      <el-form-item prop="productCategoryName" label="货品类目：">
        <el-input v-model="updateForm.productCategoryName" />
      </el-form-item>
      <el-form-item prop="name" label="货品名称：">
        <el-input v-model="updateForm.name" />
      </el-form-item>
      <el-form-item prop="price" label="价格：">
        <el-input type="number" v-model="updateForm.price" />
      </el-form-item>
      <el-form-item prop="unit" label="单位：">
        <el-input v-model="updateForm.unit" />
      </el-form-item>
      <el-form-item prop="priceRules" label="货品价格规则：">
        <el-input v-model="updateForm.priceRules" />
      </el-form-item>
      <el-form-item prop="note" label="备注信息：">
        <el-input v-model="updateForm.note" />
      </el-form-item>
    </el-form>
    <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
  </el-dialog>
</div>
<el-pagination size="default" style="float: right;margin-top: 5px" background
                 layout="total, sizes, prev, pager, next"
                 @change="handleSearchPaginationChange"
                 :total="Number(tableData.total)"
                 v-model:current-page="searchForm.pageNum"
                 v-model:page-size="searchForm.pageSize"
                 v-model:page-sizes="allocateUserPageSizes"/>

</template>
<script setup>
import { productList, productSearchList, getProductCategory, updateProd ,deleteProduct} from '../../../api';
import { nextTick, ref, reactive, onMounted, VueElement } from 'vue'
import { ElMessage } from 'element-plus';


//查询事件

const getData = () => {
  productSearchList(searchForm.value)
      .then((res) => {
        tableData.list = res.data.list;
        console.log('dangqiande', res.data)
        tableData.total = Number(res.data.total)
        
        tableData.totalPage = res.data.totalPage
        searchForm.pageNum = res.data.pageNum
        searchForm.pageSize = res.data.pageSize
        console.log('23456y', tableData)
        tableData.list = res.data.list.map(item => ({
            ...item,
            price: item.price/100,
          })
          )
          tableData.list = res.data.list.map(item => ({
            ...item,
            priceRules: tableData.list(item.priceRules)
          })
        )
        console.log(' tableData.total', tableData.total)
        console.log('tableData.totalPage',tableData.totalPage)

      })

      console.log('searchForm.value',searchForm.value)
};

// const handleSearch = async () => {
//   console.log('查询内容1', searchForm.value)
//   let res = await productSearchList(searchForm.value)
//   console.log('查询内容', res.data.list)
//   tableData.list = res.data.list;   //返回本条数据
//   console.log('返回数据',tableData.list)
//   tableData.list = res.data.list.map(item => ({
//     ...item,
//     price: item.price/100,
//   })
//   )
//   tableData.list = res.data.list.map(item => ({
//     ...item,
//     priceRules: tableData.list(item.priceRules)
//   })
// )
  
//     console.log('total',res.data.totalPage)
//     let total = res.data.totalPage
//     tableData.totalPage = res.data.totalPage
//     tableData.total =Number(res.data.total) 
//     searchForm.pageNum = res.data.pageNum
//     searchForm.pageSize = response.data.pageSize
//     console.log(' tableData.total', tableData.total)
//     console.log('tableData.totalPage',tableData.totalPage)
// }

const handleSearch = async () => {
  getData()

}
const handleSearchPaginationChange = () => {
  handleSearch();
}
//数据表数据
const tableData = reactive({
  list: [],
  totalPage:'',
  pageNum:'',
  pageSize:'',
  total:''
})

onMounted(() => {
  // productList().then(({ data }) => {
  //   console.log(data)
  //   tableData.list = data
  // })
  handleSearch();
  getProductCategoryList();
})


// 当前页变化处理
const handleCurrentChange = (val) => {

  searchForm.pageNum = val; // 更新当前页码
  handleSearch(); // 重新获取数据
};

// 页面大小变化处理
const handleSizeChange = (val) => {
  searchForm.pageSize = val; // 更新每页条目数
  handleSearch(); // 重新获取数据
};
// const parsedRules = []
const parsePriceRules = (rules) => {
  
      //return JSON.parse(rules);
     // console.log(typeof rules)
      // console.log(rules);
      //  let validJsonstring = rules.replace(/\\"/g,'"')
      //  let jsonobject = JSON.parse(validJsonstring);
      //  console.log(jsonobject);
     // const rule = JSON.parse(rules);

    // console.log('234',JSON.parse(rules))
      //console.log('34567',rules.key);
    };

//重置事件
const handleResetSearch = async () => {
  searchForm.value = {
    keywords: '',
    name: '',
    note: '',
    pageNum: 1,
    pageSize: 10,
    price: '',
    priceRules: '',
    productCategoryId: null,
    productCategoryName: '',
    sort: '',
    unit: '',
    unitWeight: '',
  };
  handleSearch();
}

let searchForm = ref({
  keywords: '',
  name: '',
  note: '',
  pageNum: 1,
  pageSize: 10,
  price: '',
  priceRules: '',
  productCategoryId: null,
  productCategoryName: '',
  sort: '',
  unit: '',
  unitWeight: '',
})

let productCategoryResult = ref([])

let productCategoryOptions = ref([])

const getProductCategoryList = async () => {
  let res = await getProductCategory()
 // console.log('商品分类', res.data)
  productCategoryResult.value = res.data
  console.log('productCategoryResult.value',productCategoryResult.value)
  productCategoryResult.value.forEach(item => {
    productCategoryOptions.value.push({
      value: item.id,
      label: item.name
    })
  })
  console.log('商品分类2322', productCategoryOptions.value)
}

//编辑数据
const dialogFormVisible = ref(false)
const formRef = ref()

const rules = reactive({
  keywords: [{ required: false, trigger: 'blur', messege: '请填写货品关键字' }],
  name: [{ required: false, trigger: 'blur', messege: '请填写货品名字' }],
  note: [{ required: false, trigger: 'change', messege: '请填写备注' }],
  price: [{ required: false, trigger: 'blur', messege: '请填填写价格' }],
  priceRules: [{ required: false, trigger: 'blur', messege: '请填写价格规则' }],
  productCategoryId: [{ required: false, trigger: 'blur', messege: '请填写名字' }],
  sort: [{ required: false, trigger: 'change', messege: '请填写排序' }],
  unit: [{ required: false, trigger: 'blur', messege: '请填写货品单位' }],
})

const updateForm = ref({
  keywords: '',
  name: '',
  note: '',
  price: 0,
  priceRules: '',
  productCategoryId: 0,
  productCategoryName: '',
  sort: 0,
  unit: '',
  unitWeight: 0
})

const open = (rowData = {}) => {
  dialogFormVisible.value = true
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData)
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData)
    }
  })
}

const confirm = async () => {
  console.log('修改内容', updateForm)
  updateForm.price = updateForm.price*100
  console.log('查看一下searchForm数据',searchForm)
  let res = await updateProd(updateForm);
  let response = await productSearchList(searchForm.value)
  console.log('查看一下',response)
  console.log(res.code)
  if (res.code == 200) {
    ElMessage({
      message: '修改成功',
      type: 'success',
      duration: 1000
    });
  } else {
    ElMessage({
      message: res.message,
      type: 'error',
      duration: 1000
    });
  }
  dialogFormVisible.value = false
  tableData.list = response.data.list;
  //tableData.list.value.price = tableData.list.price/100  
}

// //关闭弹窗回调
const beforeClose = () =>{

  dialogFormVisible.value = false
  //重置表单
  formRef.value.resetFileds()
  //tree
}

//删除数据
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('是否要删除该商品信息', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteProduct(row.id);
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    });
    handleSearch();
  } catch (error) {
    // Handle cancel or error
  }
};



</script>
<style lang="less"></style>